package cn.schoolwow.quickdao.module.database.ddl.action.flow.column.renameTableColumn;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteUpdateConnectionFlow;
import cn.schoolwow.quickdao.util.StringUtil;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class RenameTableColumnFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        String tableName = (String) flowContext.checkData("tableName");
        String oldTableColumn = (String) flowContext.checkData("oldTableColumn");
        String newTableColumn = (String) flowContext.checkData("newTableColumn");

        tableName = StringUtil.camel2Underline(tableName);
        oldTableColumn = StringUtil.camel2Underline(oldTableColumn);
        newTableColumn = StringUtil.camel2Underline(newTableColumn);

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("alter table " + quickDAOConfig.databaseContext.databaseProvider.escape(tableName));
        sqlBuilder.append(" rename column " + quickDAOConfig.databaseContext.databaseProvider.escape(oldTableColumn));
        sqlBuilder.append(" to " + quickDAOConfig.databaseContext.databaseProvider.escape(newTableColumn) + ";");

        flowContext.startFlow(new ExecuteUpdateConnectionFlow())
                .putTemporaryData("name", "重命名列")
                .putTemporaryData("sql", sqlBuilder.toString())
                .execute();
    }

    @Override
    public String name() {
        return "重命名列";
    }

}
